﻿using System.IO;
using StockUtil;
using System;
using System.Diagnostics;
using System.Runtime.InteropServices;

namespace StockLib.UserData
{
    public class BlockRegularFileSaver
    {
        public virtual void Save()
        {
            FileInfo fi = new FileInfo(StockUserData.Instance.GetFileName(UserDataType.Domain));
            FileStream fs = null;
            byte[] buffer = null;

            try
            {
                if (!fi.Directory.Exists)
                    Directory.CreateDirectory(fi.Directory.FullName);

                fs = new FileStream(fi.FullName, FileMode.Create, FileAccess.ReadWrite, FileShare.ReadWrite);

                BlockCustomFileHead head = new BlockCustomFileHead();
                head.m_wDomainNumber = (UInt16)StockBlockGroupRegular.Instance.Count;
                buffer = new byte[Marshal.SizeOf(head)];
                StructHelper.ToBytes(head, buffer, 0);
                fs.Write(buffer, 0, buffer.Length);
                buffer = null;

                buffer = new byte[Marshal.SizeOf(typeof(BlockCustomFileDomainPack))];
                BlockCustomFileDomainPack domainPack = new BlockCustomFileDomainPack();
                foreach (StockBlock domain in StockBlockGroupRegular.Instance.Values)
                {
                    BlockCustomFileDomainPack.FromInternal(domain, ref domainPack);
                    StructHelper.ToBytes(domainPack, buffer, 0);
                    fs.Write(buffer, 0, buffer.Length);
                }
                buffer = null;

                buffer = new byte[Marshal.SizeOf(typeof(BlockCustomFileStockPack))];
                BlockCustomFileStockPack stockPack = new BlockCustomFileStockPack();
                foreach (StockBlock domain in StockBlockGroupRegular.Instance.Values)
                {
                    foreach (Stock stock in domain.Values)
                    {
                        BlockCustomFileStockPack.FromInternal(stock, ref stockPack);
                        StructHelper.ToBytes(stockPack, buffer, 0);
                        fs.Write(buffer, 0, buffer.Length);
                    }
                }
                buffer = null;
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
                throw ex;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
            }
        }
    }
}
